// packageUser/pages/auth/factory-auth.js
import UserService from '../../../service/UserService';
import CommonService from '../../../service/CommonService';
import { throttle } from '../../../utils/util.js';

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    errMsg: '',
    user: {},
    region: ['广东省', '广州市', '海珠区'],
    customItem: '全部',
    validDisabled: false,
    validTxt: '获取验证码'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.userService = new UserService();
    this.commonService = new CommonService();
    const {user} = app.globalData;
    this.setData({ user });
  },
  onShow: function(){
    const { chooseCity } = app.globalData;
    const {user} = this.data;
    if (chooseCity.id) {
      user.city = chooseCity;
      user.adcode = chooseCity.id;
      this.setData({ user });
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.chooseCity = {};
  },
  validForm: function(form){
    if (!form.phone) {
      this.setData({ errMsg: '手机号码不能为空' })
      return false;
    }
    if (!form.factoryName) {
      this.setData({ errMsg: '工厂名称不能为空' })
      return false;
    }
    if (!form.cardFrontImg) {
      this.setData({ errMsg: '请上传身份证正面照' })
      return false;
    }
    if (!form.cardBackImg) {
      this.setData({ errMsg: '请上传身份证背面照' })
      return false;
    }

    if (!form.zmFiles || form.zmFiles.length < 3) {
      this.setData({ errMsg: '资质图片至少上传3张' })
      return false;
    }
    if (form.zmFiles && form.zmFiles.length > 9) {
      this.setData({ errMsg: '资质图片至多上传9张' })
      return false;
    }
    if (!form.sjFiles || form.sjFiles.length < 3) {
      this.setData({ errMsg: '实景图片至少上传3张' })
      return false;
    }
    if (form.sjFiles && form.sjFiles.length > 9) {
      this.setData({ errMsg: '实景图片至多上传9张' })
      return false;
    }
    this.setData({ errMsg: '' });
    return true;
  },
  formSubmit: function (e) {
    const _ = this;
    const {user} = this.data;
    if(!this.validForm(user)){
      return;
    }
    const param = {
      id: user.id,
      userType: 2,
      faceUrl: user.faceUrl,
      phone: user.phone,
      validCode: user.validCode,
      factoryName: user.factoryName,
      trueName: user.trueName,
      address: user.address,
      lat: user.lat,
      lng: user.lng,
      adcode: user.adcode,
      cardFrontImg: user.cardFrontImg,
      cardBackImg: user.cardBackImg,
      zmFiles: user.zmFiles,
      sjFiles: user.sjFiles,
      bankName: user.bankName,
      bankUser: user.bankUser,
      bankNum: user.bankNum,
      bankAddr: user.bankAddr,
    }
    this.userService.authApply(param).then(function (res) {
      console.log(res);
      if(res.status == 0){
        app.globalData.user.userType = 2;
        app.globalData.user.authStatus = 1;
        const { authScore } = app.globalData.setting;
        _.commonService.active(2).then(function (res) {
          if (res.status == 0) {
            wx.showModal({
              title: '认证申请成功',
              content: `你获得${authScore}枚救兵勋章`,
              showCancel: false,
              confirmText: '知道了',
              confirmColor: '#0f9bc1',
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/packageUser/pages/auth/auditting?authStatus=1'
                  })
                }
              }
            })
          }
        });
        
      }
    });
  },
  setFieldValue: function (field, value) {
    const { user } = this.data;
    user[field] = value;
    this.setData({ user });
  },
  onFaceChange: function (e) {
    this.setFieldValue("faceUrl", e.detail.value);
  },
  onPhoneChange: function (e) {
    this.setFieldValue("phone", e.detail.value);
  },
  onCode: function (e) {
    this.setFieldValue('validCode', e.detail.value);
  },
  onFactoryNameChange: function(e){
    this.setFieldValue('factoryName', e.detail.value);
  },
  onTrueNameChange: function (e) {
    this.setFieldValue('trueName', e.detail.value);
  },
  onAddressChange: function (e) {
    this.setFieldValue('address', e.detail.value);
  },
  onCardFront: function (e) {
    this.setFieldValue("cardFrontImg", e.detail.value);
  },
  onCardBack: function (e) {
    this.setFieldValue("cardBackImg", e.detail.value);
  },
  onAreaChange: function(e){
    this.setFieldValue("area", e.detail.region);
  },
  onLocationTap: function(){
    throttle(function (e) {
      wx.navigateTo({
        url: '/pages/citys/citys'
      })
    }, 1000)();
  },
  onHandCardFront: function (e) {
    this.setFieldValue("handCardFrontImg", e.detail.value);
  },
  onHandCardBack: function (e) {
    this.setFieldValue("handCardBackImg", e.detail.value);
  },
  onZmImagesChange: function(e){
    const images = e.detail.images.map(fileUrl => {
      return { fileUrl, fileType: 3};
    });
    this.setFieldValue("zmFiles", images);
  },
  onSjImagesChange: function (e) {
    const images = e.detail.images.map(fileUrl => {
      return { fileUrl, fileType: 4 };
    });
    this.setFieldValue("sjFiles", images);
  },
  onBankNameChange: function (e) {
    this.setFieldValue('bankName', e.detail.value);
  },
  onBankUserChange: function (e) {
    this.setFieldValue('bankUser', e.detail.value);
  },
  onBankNumChange: function (e) {
    this.setFieldValue('bankNum', e.detail.value);
  },
  onBankAddrChange: function (e) {
    this.setFieldValue('bankAddr', e.detail.value);
  },
  /**获取短信验证码 */
  onValidCode: function (e) {
    const _ = this;
    const { user } = this.data;
    if (!user.phone) {
      this.setData({ errMsg: '手机号码不能为空' })
      return;
    }
    this.setData({ validDisabled: true, errMsg: '' })
    this.commonService.getValidCode(user.phone).then(res => {
      if (res.status == 0) {
        let count = 60;
        const t = setInterval(() => {
          const { validTxt } = _.data;
          count--;
          _.setData({ validTxt: count });
          if (count < 0) {
            _.setData({ validTxt: '重新获取', validDisabled: false });
            clearInterval(t);
          }
        }, 1000);
      }

    })
  },
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  onLocation: function(e){
    const _ = this;
    const {user} = this.data;
    wx.chooseLocation({
      success: function (res) {
        user.address=res.address;
        user.lng = res.longitude;
        user.lat = res.latitude;
        _.setData({ user });
      }
    })
  }
})